package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.util.HttpUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.*;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import kong.unirest.json.JSONObject;
import kong.unirest.json.JSONArray;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class StudentRegisterController {
    @FXML
    private ComboBox<String> collegeCombobox;
    @FXML
    private ComboBox<String> gradeCombobox;
    @FXML
    private ComboBox<String> classCombobox;
    @FXML
    private ComboBox<String> provinceCombobox;
    @FXML
    private TextField nameTextField;
    @FXML
    private TextField telephoneNumber;
    @FXML
    private TextField email;
    @FXML
    private TextField homeAddress;
    @FXML
    private TextArea personalInformation;
    @FXML
    private TextArea note;
    @FXML
    private Label outputLabel;
    @FXML
    private RadioButton radioButton1;
    @FXML
    private RadioButton radioButton2;
    @FXML
    private DatePicker datePicker;
    @FXML
    private Label success;
    Map<Integer, String> map1 = new HashMap<>();
    Map<Integer, String> map2 = new HashMap<>();
    Map<Integer, String> map3 = new HashMap<>();
    int classId;
    private boolean collegeSelected = false;
    private boolean gradeSelected = false;
    private boolean classSelected = false;

    @FXML
    public void initialize() {
//        Globalvar.userToken ="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyMDI0OTk5OSIsImlhdCI6MTcxNjM4ODIzMiwiZXhwIjoxNzE2Mzk2ODcyfQ.V0E3phqoPt4D50tIdYQqIPJmFctoQtQHL7XJaRyTWOkpPtTNUXHRnwg7N8PCPInoF6lf23iKI_p37ehGTPZ_cA";
        ObservableList<String> items4= FXCollections.observableArrayList("安徽省","北京市","重庆市","福建省",
                "甘肃省","广东省","广西壮族自治区","贵州省","海南省", "河北省","河南省","黑龙江省", "湖北省", "湖南省",
                "吉林省","江苏省","江西省","辽宁省","内蒙古自治区", "宁夏回族自治区","青海省","山东省","山西省", "陕西省",
                "上海市","四川省","天津市","西藏自治区","新疆维吾尔自治区","云南省","浙江省","台湾省","香港特别行政区","澳门特别行政区");
        provinceCombobox.setItems(items4);
        //collegeCombobox添加项
        HttpResponse<JsonNode> response1 = HttpUtil.get(Globalvar.baseUrl+"/api/colleges")
                .header("Accept", "application/json")
                .asJson();
        JsonNode responseBody1 = response1.getBody();
        JSONArray jsonArray1 = responseBody1.getArray();
        System.out.println(response1.getBody());
        ObservableList<String> items1= FXCollections.observableArrayList();
        System.out.println(response1);
        for (int i = 0; i < jsonArray1.length(); i++) {
            JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
            String collegeName= jsonObject1.getString("collegeName");
            Integer collegeId= Integer.valueOf(jsonObject1.getString("collegeId"));
            collegeCombobox.getItems().add(collegeName);
            items1.add(collegeName);
            map1.put(collegeId, collegeName);
        }
         //设置collegeCombobox默认初始选中第一个学院
        collegeCombobox.setValue(items1.get(0));
        collegeSelected=true;
        comboBoxClickedHandler1();
        //添加三个combobox监控器，但根据层级关系进行更新相应combobox列表
        collegeCombobox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedCollege) -> {
            if (selectedCollege != null) {
                collegeSelected = true;
                gradeSelected = false;
                classSelected = false;
                comboBoxClickedHandler1();
            }
        });

        gradeCombobox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedGrade) -> {
            if (selectedGrade != null) {
                gradeSelected = true;
                classSelected = false;
                comboBoxClickedHandler2();
            }
        });

        classCombobox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedClass) -> {
            if (selectedClass != null) {
                classSelected = true;
                comboBoxClickedHandler3();
            }
        });
        note.setWrapText(true);
        personalInformation.setWrapText(true);
    }
    //根据collegeCombobox的项得到对应collegeId,添加gradesCombobox项
    public void comboBoxClickedHandler1() {
        if (collegeSelected) {
            gradeCombobox.getItems().clear();
            classCombobox.getItems().clear();
        String selectedCollege =collegeCombobox.getValue();
        String targetValue = selectedCollege;
        int collegeId =0;
        for (Map.Entry<Integer, String> entry : map1.entrySet()) {
            if (entry.getValue().equals(targetValue)) {
                collegeId = entry.getKey();
                break; // 找到匹配值后跳出循环
            }
        }
        String url = Globalvar.baseUrl +"/api/colleges/" + collegeId +"/grades";
        HttpResponse<JsonNode> response2 = HttpUtil.get(url)
                .header("Accept", "application/json")
                .asJson();
        JsonNode responseBody2 = response2.getBody();
        JSONArray jsonArray2 = responseBody2.getArray();
        ObservableList<String> items2= FXCollections.observableArrayList();
        for (int j = 0; j < jsonArray2.length(); j++) {
            JSONObject jsonObject2 = jsonArray2.getJSONObject(j);
            String gradeName= jsonObject2.getString("gradeName");
            Integer gradeId= Integer.valueOf(jsonObject2.getString("gradeId"));
            gradeCombobox.getItems().add(gradeName);
            items2.add(gradeName);
            map2.put(gradeId, gradeName);
        }
        }
    }

    //根据gradeCombobox的项得到对应gradeId,添加classCombobox项
    public void comboBoxClickedHandler2() {
        if (gradeSelected) {
            classCombobox.getItems().clear();
        String selectedGrade =gradeCombobox.getValue();
        String targetValue = selectedGrade;
        int gradeId =0;
        for (Map.Entry<Integer, String> entry : map2.entrySet()) {
            if (entry.getValue().equals(targetValue)) {
                gradeId = entry.getKey();
                break; // 找到匹配值后跳出循环
            }
        }
        String url = Globalvar.baseUrl+"/api/grades/" + gradeId +"/classes";
        HttpResponse<JsonNode> response3 = HttpUtil.get(url)
                .header("Accept", "application/json")
                .asJson();
        JsonNode responseBody3 = response3.getBody();
        JSONArray jsonArray3 = responseBody3.getArray();
        ObservableList<String> items3= FXCollections.observableArrayList();
        for (int h = 0; h < jsonArray3.length(); h++) {
            JSONObject jsonObject3 = jsonArray3.getJSONObject(h);
            String className= jsonObject3.getString("className");
            Integer classId= Integer.valueOf(jsonObject3.getString("classId"));
            classCombobox.getItems().add(className);
            items3.add(className);
            map3.put(classId, className);
        }
        }
    }

    //根据collegeCombobox的项得到对应collegeId,将classId传给后端
    public void comboBoxClickedHandler3() {
        String selectedClass =classCombobox.getValue();
        String targetValue = selectedClass;
        for (Map.Entry<Integer, String> entry : map3.entrySet()) {
            if (entry.getValue().equals(targetValue)) {
                classId = entry.getKey();
                break; // 找到匹配值后跳出循环
            }
        }
    }

    //handleButtonClick实现点击注册按钮，若姓名，性别，生源地，出生日期中存在未填写项，均不予通过并提示相关内容
    public void handleButtonClick() {
        boolean textFieldEmpty = nameTextField.getText().isEmpty();
        boolean comboBoxEmpty = provinceCombobox.getValue() == null;
        boolean radioButtonsSelected = radioButton1.isSelected() || radioButton2.isSelected();
        boolean datePickerEmpty = datePicker.getValue() == null;

        if (textFieldEmpty && comboBoxEmpty  && !radioButtonsSelected && datePickerEmpty) {
            outputLabel.setText("姓名不能为空！");
            nameTextField.setStyle("-fx-border-color: red;");
            provinceCombobox.setStyle("-fx-border-color:  #b1b1b1; -fx-background-color: #ffffff;");
            radioButton1.setStyle("-fx-border-color: inherit;");
            radioButton2.setStyle("-fx-border-color: inherit;");
            datePicker.setStyle("-fx-border-color: inherit;");
        }  else if (textFieldEmpty) {
            outputLabel.setText("姓名不能为空！");
            nameTextField.setStyle("-fx-border-color: red;");
            provinceCombobox.setStyle("-fx-border-color: #b1b1b1; -fx-background-color: #ffffff;");
            radioButton1.setStyle("-fx-border-color: inherit;");
            radioButton2.setStyle("-fx-border-color: inherit;");
            datePicker.setStyle("-fx-border-color: inherit;");
        } else if (comboBoxEmpty) {
            outputLabel.setText("生源地未选择！");
            nameTextField.setStyle("-fx-border-color: inherit;");
            provinceCombobox.setStyle("-fx-border-color: red; -fx-background-color: #ffffff;");
            radioButton1.setStyle("-fx-border-color: inherit;");
            radioButton2.setStyle("-fx-border-color: inherit;");
            datePicker.setStyle("-fx-border-color: inherit;");
        }else if (!radioButtonsSelected) {
            outputLabel.setText("性别未选择！");
            nameTextField.setStyle("-fx-border-color: inherit;");
            provinceCombobox.setStyle("-fx-border-color: #b1b1b1; -fx-background-color: #ffffff;");
            radioButton1.setStyle("-fx-border-color: red;");
            radioButton2.setStyle("-fx-border-color: red;");
            datePicker.setStyle("-fx-border-color: inherit;");
        } else if (datePickerEmpty) {
            outputLabel.setText("出生日期未选择！");
            nameTextField.setStyle("-fx-border-color: inherit;");
            provinceCombobox.setStyle("-fx-border-color: #b1b1b1; -fx-background-color: #ffffff;");
            radioButton1.setStyle("-fx-border-color: inherit;");
            radioButton2.setStyle("-fx-border-color: inherit;");
            datePicker.setStyle("-fx-border-color: red;");
        }
        else {
            outputLabel.setText("");
            nameTextField.setStyle("-fx-border-color: inherit;");
            provinceCombobox.setStyle("-fx-border-color: #b1b1b1; -fx-background-color: #ffffff;");
            radioButton1.setStyle("-fx-border-color: inherit;");
            radioButton2.setStyle("-fx-border-color: inherit;");
            datePicker.setStyle("-fx-border-color: inherit;");

             //若四个必填项都已填，则将数据传给后端
            JSONObject data = new JSONObject();
            String name=nameTextField.getText();
            if(classCombobox.getValue()==null)
                classId=1;
            String gender;
            if(radioButton1.isSelected())
                gender="male";
            else
                gender="female";
            String province=provinceCombobox.getValue();
            String birthday= String.valueOf(datePicker.getValue());
            if(email.getText()==null)
                email.setText("john.doe@example.com");
            String email1=email.getText();
            if (telephoneNumber.getText() == null)
                telephoneNumber.setText("1234567890");
            String telephone=telephoneNumber.getText();
            if (homeAddress.getText() == null)
                homeAddress.setText("123 Main St, City");
            String homeAddress1=homeAddress.getText();
            if (personalInformation.getText() == null)
                personalInformation.setText("Some personal information here");
            String personalInfo=personalInformation.getText();
            data.put("name", name);
            data.put("classId", classId);
            data.put("province",province);
            data.put("gender", gender);
            data.put("birthday", birthday);
            data.put("email", email1);
            data.put("telephone", telephone);
            data.put("homeAddress", homeAddress1);
            data.put("personalInfo", personalInfo);
            HttpResponse<JsonNode> response=HttpUtil.post(Globalvar.baseUrl+"/api/students/register")
                    .header("Content-Type", "application/json")
                    .body(data)
                    .asJson();
            int statusCode = response.getStatus();
            success.setVisible(false);
            if(statusCode == 200) {
                success.setVisible(true);

                // 注册成功给用户提示，维持3秒
                Timer successTimer = new Timer();
                successTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        success.setVisible(false);
                    }
                }, 3000); // 3000 milliseconds = 3 seconds
            }
            System.out.println("Status code: " + statusCode);
            System.out.println("Request body sent: " + data);
        }
    }
}

